/**
 * Created by limeng on 16/8/30.
 */
delegateApp.controller('ArticleListCtrl', function ($scope, $http) {
    $scope.pageSize = 10;
    $scope.pageNo = 1;
    $scope.inputPageNo = 1;
    $scope.pageCount = 1;
    $scope.articles = [];
    $scope.searchMap = {};

    $scope.updateContent = function() {
        $scope.searchMap.pageSize = parseInt($scope.pageSize);
        $scope.searchMap.pageNo = parseInt($scope.pageNo);
        $http.post('/article/search', $scope.searchMap).success(
            function (data) {
                if (data.state == true) {
                    $scope.articles = data.list;
                    $scope.pageCount = data.pageCount;
                } else {
                    showAlert('查询失败', '原因是:' + data.result);
                }
            }
        ).error(
            function () {
                showAlert('查询失败', '请联系开发者进行维护');
            }
        );
    };

    $scope.previousPage = function () {
        $scope.pageNo = ($scope.pageNo - 1) < 1 ? 1 : --$scope.pageNo;
        $scope.updateContent();
    };
    $scope.nextPage = function() {
        $scope.pageNo = ($scope.pageNo + 1) >= $scope.pageCount ? $scope.pageCount : ++$scope.pageNo;
        $scope.updateContent();
    };
    $scope.jumpPage = function () {
        if ($scope.inputPageNo > 0 && $scope.inputPageNo <= $scope.pageCount) {
            $scope.pageNo = parseInt($scope.inputPageNo);
            $scope.updateContent();
        } else {
            $scope.inputPageNo = 1;
        }
    };

    $scope.deleteArticle = function (article) {
        var articleId = article.id;
        bootbox.confirm("真的要删除这个文章吗?", function (res) {
            if (res) {
                $http.delete("/article/"+articleId).success(function (data) {
                    if (data.state) {
                        bootbox.alert("删除成功!");
                        $scope.updateContent();
                    }
                }).error(function() {
                    bootbox.alert("服务器没有响应!");
                });
            }
        });
    };

    $scope.updateContent();
});